package com.catherine.mvp_base_component.base;

import com.catherine.mvp_base_component.net.RetrofitManager;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;

/**
 * @Description:基类路由层
 * @Author: hhh
 * @CreateDate: 2020/9/15
 */
public class BasePresenter<V extends BaseView> {

    private CompositeDisposable compositeDisposable;
    public V baseView;


    protected RetrofitManager onlyChainRetrofitManager = RetrofitManager.getOnlyChainInstance();
    protected RetrofitManager ethChainRetrofitManager = RetrofitManager.getEthChainInstance();
    protected RetrofitManager phpServerRetrofitManager = RetrofitManager.getPhpServerInstance();

    public BasePresenter(V baseView) {
        this.baseView = baseView;
    }

    /**
     * 解除绑定
     */
    void detachView() {
        baseView = null;
        removeDisposable();
    }

    /**
     * 返回 view
     */
    public V getBaseView() {
        return baseView;
    }

    /**
     * 在io线程执行，在切换到回主线程
     * @param observable
     * @param observer
     */
    @SuppressWarnings("unchecked")
    protected void addDisposableObserveOnMain(Observable<?> observable, BaseObserver observer) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable
                .add(observable.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeWith(observer));
    }

    /**
     * 使用发射器，先加载数据库中的数据，然后再去请求网络数据
     * @param dbObservable
     * @param netObservable
     * @param observer
     */
    @SuppressWarnings("unchecked")
    protected void addDisposableObserveOnMainByConcat(Observable<?> dbObservable,Observable<?> netObservable, BaseObserver observer) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable
                .add(Observable.concat(dbObservable,netObservable)
                .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeWith(observer));
    }

    /**
     * 在io线程执行
     * @param observable
     * @param observer
     */
    @SuppressWarnings("unchecked")
    protected void addDisposableObserveOnIo(Observable<?> observable, BaseObserver observer) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable
                .add(observable.subscribeOn(Schedulers.io())
                        .subscribeWith(observer));
    }

    private void removeDisposable() {
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
        }
    }

}
